﻿using Nirvana;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SortingLayerHelper : MonoBehaviour
{
    [Tooltip("The sorting layer you want to select.")]
    [SerializeField]
    [SortLayer]
    private int sortlayer;

    [Tooltip("The sorting order you want to override.")]
    [SerializeField]
    private int sortingOrder;
    //记录初始order
    private Dictionary<Renderer, int> allRenders = new Dictionary<Renderer, int>();
    public int SortingOrder
    {
        get
        {
            return this.sortingOrder;
        }
        set
        {
            this.sortingOrder = value;
            this.Sort();
        }
    }

    // Start is called before the first frame update
    private void Awake()
    {
        var _renders = GetComponentsInChildren<Renderer>(true);
        foreach (Renderer renderer in _renders)
        {
            allRenders.Add(renderer, renderer.sortingOrder);
        }

        //this.Sort();
    }

    //private void OnValidate()
    //{
    //    this.Sort();
    //}
    private void OnEnable()
    {
        this.Sort();
    }

    private void Sort()
    {
        if (this.allRenders == null || allRenders.Count == 0)
        {
            return;
        }
        var renders = this.allRenders.Keys;
        foreach (var p in renders)
        {
            p.sortingLayerID = this.sortlayer;
            p.sortingOrder = this.allRenders[p] + this.sortingOrder;
        }
    }

    private void OnDestroy()
    {
        allRenders.Clear();
        allRenders = null;
    }
}
